<template>
  <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft"
               style="--van-nav-bar-text-color: #FFC000;--van-nav-bar-icon-color:#FFC000"></van-nav-bar>
  <div v-if="editUser.editKey === 'ubankcard'" style="text-align: center;margin-top: 50px">
    <van-uploader
        preview-size="60"
        v-model="fileList"
        :max-count="1"
        :after-read="afterRead as any"
    />
  </div>
  <van-form @submit="onSubmit" style="padding-top: 56px">
    <van-field
        v-model="editUser.currentValue as string"
        :name="`${editUser.editKey}`"
        :label="`${editUser.editName}`"
        :placeholder="`请输入${editUser.editName}`"
        :rules="generateValidationRules(<string>editUser?.editKey) as any"
    />
    <div style="margin: 16px;">
      <van-button round block type="primary" color="#F9752D" native-type="submit">
        更新
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import myAxios from "../plugins/myAxios";
import { Toast } from "vant";
import { getCurrentUser } from "../services/user";
import { getCurrentUser2 } from "@/services/user2.ts";
import axios from 'axios';
const fileList = ref([] as any[]);

const route = useRoute();
const router = useRouter();

const editUser = ref({
  editKey: route.query.editKey,
  currentValue: route.query.currentValue,
  editName: route.query.editName,
});

const afterRead = (file: { content: string }) => {
  console.log('上传成功', file);
  callBaiduOCR(file.content);
};
const onSubmit = async () => {
  const currentUser = await getCurrentUser();
  if (!currentUser) {
    router.push({
      path: '/phone',
      replace: true,
    });
    // @ts-ignore
  } else if (currentUser?.code === 40100 || currentUser.data == null) {
    router.push({
      path: '/phone',
      replace: true,
    });
  }


  const res = await myAxios.post('/update', {
    ubankcard: editUser.value.editKey === 'ubankcard' ? editUser.value.currentValue : "",
    uname: editUser.value.editKey  as string === 'uname' ? editUser.value.currentValue : "",
    uphone: editUser.value.editKey  as string=== 'uphone' ? editUser.value.currentValue : "",
    udepartment: editUser.value.editKey  as string=== 'udepartment' ? editUser.value.currentValue : "",
    uclass: editUser.value.editKey  as string=== 'uclass' ? editUser.value.currentValue : "",
    namePrivacy: editUser.value.editKey  as string=== 'namePrivacy' ? editUser.value.currentValue : "",
    uid: ""
  });
  // @ts-ignore
  if (res.code === 200 && res.data) {
    router.replace("/update");
  } else {
    console.error("Update failed");
  }
};

const callBaiduOCR = (base64Image: string) => {
  const apiKey = 'UGZn6t4yHOY0BGcwhTvk7Cp5';
  const secretKey = 'aHC0tqE4Yxj6cpaCWyPXBTYeGLrLshk6';
  const accessToken = '24.136b98c343a02d04be47c5962bb81090.2592000.1711249591.282335-50715863';
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  const data = new URLSearchParams();
  data.append('image', base64Image);
  data.append('access_token', accessToken);

  axios.post('https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard', data, { headers })
      .then(response => {
        console.log('OCR响应', response.data);
        // 在这里处理响应，更新视图或进行其他逻辑操作
        if (response.data && response.data.result && response.data.result.bank_card_number) {
          const bankCardNumber = response.data.result.bank_card_number.replace(/\s/g, ''); // 去除空格
          editUser.value.currentValue = bankCardNumber;
        }
      })
      .catch(error => {
        console.error('OCR请求失败', error);
        // 处理错误，例如提示用户或进行其他错误处理
      });
};

const onClickLeft = () => {
  router.back();
};

onMounted(async () => {
  const res = await getCurrentUser2();
  // @ts-ignore
  if (res?.code === 40100 || res.data == null) {
    router.push({
      path: '/check',
      replace: true,
    });
  }
  // @ts-ignore
  if (res.code === 200) {
    console.log("Login successful");
  }
});

const generateValidationRules = (editKey: string) => {
  if (editKey === 'uphone') {
    return [{
      pattern: /^[0-9]{11}$/,
      message: '请输入正确的11位手机号',
      trigger: 'change'
    }];
  } else if (editKey === 'ubankcard') {
    return [{
      pattern: /^[0-9]{19}$/,
      message: '请输入正确的校园卡号',
      trigger: 'change'
    }];
  } else {
    // 默认规则或其他规则
    return [];
  }
};
</script>

<style scoped>

</style>
